﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Mvc3App.Dominio;

namespace Mvc3App.Repositorio
{
    public class SocioEFRepository : IRepository<Socio>
    {
        private EFDbContext _context = new EFDbContext();

        #region Implementation of IRepository<Socio>

        public Socio GetOne(object id)
        {
            return _context.Socio.SingleOrDefault(x => x.Id == (int)id);
        }

        public long Count()
        {
            return Socios.Count();
        }

        public void Add(Socio entity)
        {
            if (entity.Id == 0)
            {
                _context.Socio.Add(entity);
            }
            else
            {
                _context.Entry(entity).State = EntityState.Modified;
            }

            _context.SaveChanges();
        }

        public void Add(IEnumerable<Socio> entities)
        {
            foreach (var entity in entities)
            {
                Add(entity);
            }
        }

        public void Update(Socio entity)
        {
            Add(entity);
        }

        public void Delete(object id)
        {
            var entity = GetOne(id);
            Delete(entity);
        }

        public void Delete(Socio entity)
        {
            _context.Socio.Remove(entity);
            _context.SaveChanges();
        }

        public IEnumerable<Socio> GetSlice(int slice, int quantity, string order, bool ascending)
        {
            return _context.Socio.OrderBy(x => x.Id)
                .Skip((slice - 1) * quantity)
                .Take(quantity);
        }

        #endregion

        public IEnumerable<Socio> GetSliceByFilter(int slice, int quantity, Func<Socio, IComparable> order, bool ascending, string name, string lastname, string dni)
        {
            var resultFilters = GetByFiltro(name, lastname, dni);
            IEnumerable<Socio> result = ascending ? resultFilters.OrderBy(order) : resultFilters.OrderByDescending(order);
            return result.Skip((slice - 1) * quantity).Take(quantity);
        }

        public IEnumerable<Socio> GetByFiltro(string name, string lastname, string dni)
        {
            return _context.Socio.Where(x => (string.IsNullOrEmpty(name) || x.Nombre.Contains(name)) &&
                    (string.IsNullOrEmpty(lastname) || x.Apellido.Contains(lastname)) &&
                    (string.IsNullOrEmpty(dni) || x.Documento.Contains(dni)));
        }

        public IQueryable<Socio> Socios
        {
            get { return _context.Socio; }
        } 
    }
}